package com.ir.mirrajabi.searchdialog.sample.slice;

import com.ir.mirrajabi.searchdialog.sample.ResourceTable;
import com.ir.mirrajabi.searchdialog.sample.customdialog.ContactModel;
import com.ir.mirrajabi.searchdialog.sample.customdialog.ContactSearchDialogCompat;
import com.ir.mirrajabi.searchdialog.sample.model.SampleModel;
import com.ir.mirrajabi.searchdialog.sample.model.UserModel;

import ir.mirrajabi.searchdialog.SimpleSearchDialogCompat;
import ir.mirrajabi.searchdialog.StringsHelper;
import ir.mirrajabi.searchdialog.core.BaseFilter;
import ir.mirrajabi.searchdialog.core.BaseSearchDialogCompat;
import ir.mirrajabi.searchdialog.core.SearchResultListener;
import ir.mirrajabi.searchdialog.core.Searchable;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import ohos.agp.window.dialog.ToastDialog;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;

import java.io.IOException;
import java.util.ArrayList;

/**
 * MainAbilitySlice
 */
public class MainAbilitySlice extends AbilitySlice implements Component.ClickedListener {
    private EventHandler handler = new EventHandler(EventRunner.getMainEventRunner());

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);

        findComponentById(ResourceTable.Id_btn1).setClickedListener(this);
        findComponentById(ResourceTable.Id_btn2).setClickedListener(this);
        findComponentById(ResourceTable.Id_btn3).setClickedListener(this);
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    @Override
    public void onClick(Component component) {
        switch (component.getId()) {
            case ResourceTable.Id_btn1:
                provideSimpleDialog();
                break;
            case ResourceTable.Id_btn2:
                provideCustomContactDialog();
                break;
            case ResourceTable.Id_btn3:
                provideSimpleDialogWithApiCalls();
                break;
        }
    }

    /**
     * 基础已实现弹框，拿来就可以用
     */
    private void provideSimpleDialog() {
        SimpleSearchDialogCompat dialog =
                new SimpleSearchDialogCompat(
                        getContext(),
                        "Search...",
                        "What are you looking for...?",
                        null,
                        createSampleData(),
                        new SearchResultListener<SampleModel>() {
                            @Override
                            public void onSelected(BaseSearchDialogCompat dialog, SampleModel item, int position) {
                                dialog.hide();
                                toast(item.getTitle());
                            }
                        });
        dialog.show();
    }

    /**
     * 自定义弹框
     */
    void provideCustomContactDialog() {
        new ContactSearchDialogCompat<>(
                        getAbility(),
                        "Search...",
                        "What are you looking for...?",
                        null,
                        createSampleContacts(),
                        new SearchResultListener<ContactModel>() {
                            @Override
                            public void onSelected(BaseSearchDialogCompat dialog, ContactModel item, int position) {
                                toast(item.getTitle());
                                dialog.hide();
                                dialog.destroy();
                            }
                        })
                .show();
    }

    private ArrayList<SampleModel> createSampleData() {
        ArrayList<SampleModel> items = new ArrayList<>();
        items.add(new SampleModel("First item"));
        items.add(new SampleModel("Second item"));
        items.add(new SampleModel("Third item"));
        items.add(new SampleModel("The ultimate item"));
        items.add(new SampleModel("Last item"));
        items.add(new SampleModel("Lorem ipsum"));
        items.add(new SampleModel("Dolor sit"));
        items.add(new SampleModel("Some random word"));
        items.add(new SampleModel("guess who's back"));
        return items;
    }

    private ArrayList<ContactModel> createSampleContacts() {
        ArrayList<ContactModel> items = new ArrayList<>();
        // Thanks to https://randomuser.me for the images
        items.add(new ContactModel("First item", ""));
        items.add(new ContactModel("Second item", ""));
        items.add(new ContactModel("Third item", ""));
        items.add(new ContactModel("The ultimate item", ""));
        items.add(new ContactModel("Last item", ""));
        items.add(new ContactModel("Lorem ipsum", ""));
        items.add(new ContactModel("Dolor sit", ""));
        items.add(new ContactModel("Some random word", ""));
        items.add(new ContactModel("guess who's back", ""));
        return items;
    }

    private void toast(String string) {
        new ToastDialog(getContext()).setContentText(string).show();
    }

    /**
     * 可网络请求，自定义过滤器弹框
     */
    private void provideSimpleDialogWithApiCalls() {
        final SimpleSearchDialogCompat<UserModel> searchDialog =
                new SimpleSearchDialogCompat(
                        getContext(),
                        "Search...",
                        "What are you looking for...?",
                        null,
                        new ArrayList(),
                        new SearchResultListener<Searchable>() {
                            @Override
                            public void onSelected(BaseSearchDialogCompat dialog, Searchable item, int position) {
                                toast(item.getTitle());
                                dialog.hide();
                                dialog.destroy();
                            }
                        });
        BaseFilter apiFilter =
                new BaseFilter() {
                    @Override
                    protected FilterResults executeFiltering(CharSequence charSequence) {
                        doBeforeFiltering();
                        FilterResults results = new FilterResults();
                        results.results = new ArrayList<UserModel>();
                        results.size = 0;
                        try {
                            // 这里可放置网络解析的数据
                            ArrayList<UserModel> users = getUsers();
                            if (users != null) {
                                results.results = users;
                                results.size = users.size();
                            }
                            return results;
                        } catch (Exception e) {
                            String error = e.getMessage();
                            return null;
                        }
                    }

                    @Override
                    protected void publishFilterResults(CharSequence charSequence, FilterResults filterResults) {
                        if (filterResults != null) {
                            ArrayList<UserModel> filtered = (ArrayList<UserModel>) filterResults.results;
                            if (filtered != null) {
                                searchDialog.getFilterResultListener().onFilter(filtered);
                            }
                            handler.postTask(
                                    new Runnable() {
                                        @Override
                                        public void run() {
                                            doAfterFiltering();
                                        }
                                    },
                                    2000);
                        }
                    }
                };
        searchDialog.setFilter(apiFilter);
        searchDialog.show();
    }

    private ArrayList<UserModel> getUsers() {
        ArrayList<UserModel> userModels = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            UserModel userModel = new UserModel(20, i + 1, "numwzy", "chen", new ArrayList<>());
            userModels.add(userModel);
        }
        UserModel userModel1 = new UserModel(20, 12, "abcdef", "chen", new ArrayList<>());
        userModels.add(userModel1);

        UserModel userModel2 = new UserModel(20, 13 + 1, "defghi", "chen", new ArrayList<>());
        userModels.add(userModel2);
        UserModel userModel3 = new UserModel(20, 14 + 1, "ghiopqrst", "chen", new ArrayList<>());
        userModels.add(userModel3);
        UserModel userModel4 = new UserModel(20, 15 + 1, "jklmn", "chen", new ArrayList<>());
        userModels.add(userModel4);

        return userModels;
    }
}
